package com.mingqijia.gassafety.authority.security.config;

import com.mingqijia.gassafety.authority.security.filter.JwtAuthenticationTokenFilter;
import com.mingqijia.gassafety.authority.security.filter.JwtLoginAuthenticationFilter;
import com.mingqijia.gassafety.shared.constant.Constants;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandlerImpl;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * 服务安全配置
 * @author Damon S.
 * @version v1.0.1
 * @date 2020年07月12日 15:45
 */
@Configuration
@RequiredArgsConstructor
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

    private final AuthenticationEntryPoint unauthorizedEntry;
    private final PasswordEncoder passwordEncoder;
    private final LogoutSuccessHandler logoutSuccessHandler;
    private final UserDetailsService userDetailsService;
    private final JwtLoginAuthenticationFilter jwtLoginFilter;
    private final JwtAuthenticationTokenFilter jwtTokenFilter;


    private static final String[] AUTH_RESOURCES = {
            "/swagger-resources/**", "/**/api-docs/**", "/v2/api-docs",
            "/swagger-ui/**", "/**/*.html", "/**/*.css", "/**/*.js", "/webSocket/**"
            , "/hangzhou/v1/irs/**"
    };

    /*** 配置userDetails的数据源，密码加密格式 */
    @Override
    public void configure(AuthenticationManagerBuilder builder) throws Exception {
        builder.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 用于解决当接口返回值为String时，beforeBodyWrite方法类型转换失败
        converters.add(Constants.INT_ZERO, new MappingJackson2HttpMessageConverter());
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowCredentials(false)
                .maxAge(3600);
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    /**
     * 忽略拦截url或静态资源文件夹
     * web.ignoring(): 会直接过滤该url - 将不会经过Spring Security过滤器链
     * http.permitAll(): 不会绕开springsecurity验证，相当于是允许该路径通过
     */
    @Override
    public void configure(WebSecurity webSecurity) throws Exception {
        webSecurity.ignoring().antMatchers(HttpMethod.GET, AUTH_RESOURCES);
    }

    /**
     * anyRequest          |   匹配所有请求路径
     * access              |   SpringEl表达式结果为true时可以访问
     * anonymous           |   匿名可以访问
     * denyAll             |   用户不能访问
     * fullyAuthenticated  |   用户完全认证可以访问（非remember-me下自动登录）
     * hasAnyAuthority     |   如果有参数，参数表示权限，则其中任何一个权限可以访问
     * hasAnyRole          |   如果有参数，参数表示角色，则其中任何一个角色可以访问
     * hasAuthority        |   如果有参数，参数表示权限，则其权限可以访问
     * hasIpAddress        |   如果有参数，参数表示IP地址，如果用户IP和参数匹配，则可以访问
     * hasRole             |   如果有参数，参数表示角色，则其角色可以访问
     * permitAll           |   用户可以任意访问
     * rememberMe          |   允许通过remember-me登录的用户访问
     * authenticated       |   用户登录后可访问
     */
    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        // 由于使用的是JWT，我们这里1.禁用CSRF, 2.开启跨域，3.开启自动登录 - cookie储存方式
        httpSecurity.csrf().disable().cors().and().rememberMe();
        // 防止iframe 造成跨域, 禁用缓存
        httpSecurity.headers().frameOptions().disable().cacheControl().disable();
        // 不创建会话 - 即通过前端传token到后台过滤器中验证是否存在访问权限
        httpSecurity.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // 未登录认证异常
        httpSecurity.exceptionHandling().authenticationEntryPoint(unauthorizedEntry);
        // 登录过后访问无权限的接口时自定义403响应内容
        httpSecurity.exceptionHandling().accessDeniedHandler(new AccessDeniedHandlerImpl());

        ExpressionUrlAuthorizationConfigurer<HttpSecurity>.ExpressionInterceptUrlRegistry
                registry = httpSecurity.authorizeRequests();
        registry.and().logout().logoutUrl("/console/v1/oauth/logout")
                .logoutSuccessHandler(logoutSuccessHandler);
        registry.antMatchers("/inner/v1/**").permitAll();
        registry.antMatchers("/iot/alarm/**").permitAll();
        registry.antMatchers("/openapi/v1/**").permitAll();
        registry.antMatchers("/console/v1/oauth/captcha").permitAll();
        registry.antMatchers("/console/v1/common/**").permitAll();
        registry.antMatchers("/console/v1/home").fullyAuthenticated();
        registry.antMatchers("/webSocket/notify/**").permitAll();
        registry.antMatchers("/console/v1/openapi/workorder/**").permitAll();
        // 其余所有请求都需要认证
        registry.anyRequest().authenticated();

        // 添加token验证过滤器
        httpSecurity.addFilterBefore(jwtTokenFilter, LogoutFilter.class);
        // 自定义过滤器在登录时认证用户名、密码
        httpSecurity.addFilterAt(jwtLoginFilter, UsernamePasswordAuthenticationFilter.class);
    }
}


